<?php
class PersonnagesManager {
	private $_db;  // instance de PDO
	
	public function __construct($db) {
		$this->setDb($db);
		}
	
	public function add(Personnage $perso) {
		$q = $this->_db->prepare('INSERT INTO personnages SET nom=:nom, force=:force, degats=:degats, niveau=:niveau, experience=:experience');
		
		$q->bindValue(':nom', $perso->getNom());
		$q->bindValue(':force', $perso->getForce(), PDO::PARAM_INT);
		$q->bindValue(':degats', $perso->getDegats(), PDO::PARAM_INT);
		$q->bindValue(':niveau', $perso->getNiveau(), PDO::PARAM_INT);
		$q->bindValue(':experience', $perso->getExperience(), PDO::PARAM_INT);
		
		$q->execute();
		
		$perso->hydrate(array('id'=>$this->_db->lastInsertId(), 'degats'=>0));
		
		
	}
	
	public function delete(Personnage $perso) {
		$this->_db->exec('DELETE FROM personnages WHERE id='.$perso->getId());
	}
	
	public function get($id) {
		$id = (int) $id;
		
		$q = $this->_db->query('SELECT id, nom, force, degats, niveau, experience FROM personnages WHERE id='.$id); 
		$donnes = $q->fetch(PDO::FETCH_ASSOC);
		
		return new Personnage($donnees);
		
	}
	
	public function getList() {
		$persos = array();
		$q = $this->_db->query('SELECT id, nom, force, degats, niveau, experience FROM personnages ORDER BY nom');
		
		while ($donnees = $q->fetch(PDO::FETCH_ASSOC)) {
			$persos[] = new Personnage($donnees);
		}
		return $persos; 
	}
	
	public function update(Personnage $perso) {
		$q = $this->_db->prepare('UPDATE personnages SET force = :force, degats = :degats, niveau = :niveau, experience = :experience WHERE id = :id');
		
		$q->bindValue(':force', $perso->getForce(), PDO::PARAM_INT);
		$q->bindValue(':degats', $perso->getDegats(), PDO::PARAM_INT);
		$q->bindValue(':niveau', $perso->getNiveau(), PDO::PARAM_INT);
		$q->bindValue(':experience', $perso->getExperience(), PDO::PARAM_INT);
		$q->bindValue(':id', $perso->getId(), PDO::PARAM_INT);
		
		$q->execute();
	}
	
	public function setDb(PDO $db) {
		$this->_db = $db;
	}
}
?>



